package org.example.backend.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.example.backend.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * JWT拦截器
 */
@Component
@Slf4j
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;

    @Value("${jwt.header}")
    private String header;

    @Value("${jwt.tokenPrefix}")
    private String tokenPrefix;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求路径
        String requestURI = request.getRequestURI();
        log.info("请求路径: {}", requestURI);

        // 如果是注册、登录等不需要验证的路径，直接放行
        if (requestURI.contains("/auth/register") ||
            requestURI.contains("/api/error") ||
            requestURI.contains("/auth/login") ||
            requestURI.contains("/auth/emailLogin") ||
            requestURI.contains("/auth/sendCode") ||
            requestURI.contains("/auth/verifyCode")) {
            log.info("不需要验证的路径，直接放行: {}", requestURI);
            return true;
        }

        // 从请求头中获取token
        String token = request.getHeader(header);
        // 如果token为空或者不是以Bearer开头，则返回401
        if (token == null || !token.startsWith(tokenPrefix)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("Unauthorized");
            return false;
        }
        // 去掉Bearer前缀
        token = token.substring(tokenPrefix.length());
        try {
            // 验证token是否过期
            if (jwtUtil.isTokenExpired(token)) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.getWriter().write("Token expired");
                return false;
            }
            // 将用户信息存入request
            request.setAttribute("userId", jwtUtil.getUserIdFromToken(token));
            request.setAttribute("username", jwtUtil.getUsernameFromToken(token));
            request.setAttribute("role", jwtUtil.getRoleFromToken(token));
            return true;
        } catch (Exception e) {
            log.error("Token验证失败", e);
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("Invalid token");
            return false;
        }
    }
}
